/**
 *
 */
package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.ErrandApi;
import com.ybkj.daijia.config.FreightApi;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.config.ZhuanApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.event.model.ActivityGiftCouponEvent;
import com.ybkj.daijia.server.mapper.CouponMapper;
import com.ybkj.daijia.server.mapper.OrderMapper;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.sales.CouponRule.CouponType;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.ErrandUpService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author Shine
 *
 */
@Service
public class DefaultCouponService implements CouponService {

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private PassengerApi passengerApi;

    @Autowired
    private ZhuanApi zhuanApi;

    @Autowired
    private ErrandApi errandApi;

    @Autowired
    private FreightApi freightApi;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private ErrandUpService errandService;

    @Override
    public Coupon findByCode(String code) {
        Result<Coupon> result = salesApi.findOneCouponByCode(code);

        return result.getResult();
    }


    @Override
    public Coupon findOne(Long id) {
        Result<Coupon> result = salesApi.findOneCoupon(id);

        return result.getResult();
    }


    @Override
    public Result<Coupon> update(Coupon coupon) {

        return salesApi.updateCoupon(coupon);

    }

    @Override
    public Page<Coupon> queryByPassenger(Long passengerId, Integer page, Integer limit,
        Integer status) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.QUERY_COUPON
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(limit));
        if (null != status) {
            kv.put("status", String.valueOf(status));
            builder.append("&status={status}");
        }

        kv.put("passengerId", String.valueOf(passengerId));
        builder.append("&passengerId={passengerId}");

        String result = salesApi.get(builder.toString(), kv, settingUtils.get());
        List<Coupon> list = new ArrayList<Coupon>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code1 = jo.getInt("code");
            if (code1 == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Coupon>>() {
                }.getType());
                if (CollectionUtils.isNotEmpty(list)) {
                    for (Coupon coupon : list) {
                        if (coupon.getCouponRule().getTimeStatus()
                            .equals(CouponRule.COUPONRULE_STATUS_OVERDUE) || coupon.getCouponRule()
                            .isLapsed()) {
                            coupon.setStatus(Coupon.COUPON_STATUS_INVALID);
                        }
                        CouponRule rule = coupon.getCouponRule();
                        rule.setMoney(coupon.getCouponPrice());
                        if (CouponRule.CouponType.paotui.compareTo(rule.getCouponType()) == 0
                            && null != rule.getCouponTypeId()) {
                            com.ybkj.daijia.server.errand.OrderType orderType = errandService
                                .findByTypeId(rule.getCouponTypeId());
                            if (null != orderType) {
                                rule.setCouponTypeName(orderType.getTypeName());
                            }
                        }

                    }
                }

            }

        }

        return new PageImpl<Coupon>(list, pageable, total);

    }

    @Override
    public List<Coupon> listByPassenger(
        Long passengerId, CouponType couponType, Long couponTypeId, String linesId) {

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.FIND_VALID_COUPON
            + "?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("passengerId", String.valueOf(passengerId));
        builder.append("&passengerId={passengerId}");

        if (null != couponType) {
            kv.put("couponType", couponType.toString());
            builder.append("&couponType={couponType}");
        }
        if (null != couponTypeId) {
            kv.put("couponTypeId", String.valueOf(couponTypeId));
            builder.append("&couponTypeId={couponTypeId}");
        }
        if (StringUtils.isNotBlank(linesId)) {
            kv.put("linesId", linesId);
            builder.append("&linesId={linesId}");
        }

        String result = salesApi.get(builder.toString(), kv, settingUtils.get());
        List<Coupon> list = new ArrayList<Coupon>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code1 = jo.getInt("code");
            if (code1 == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Coupon>>() {
                }.getType());
            }

        }

        return list;
    }


    @Override
    public BigDecimal sumMoneyByPassenger(Long passengerId) {

        return salesApi.sumMoneyByPassenger(passengerId);

    }

    @Override
    public void listMass(Long couponRuleId, Integer amount) {

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.MASS_COUPON
            + ".json?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        if (couponRuleId != null && couponRuleId != 0) {
            kv.put("couponRuleId", String.valueOf(couponRuleId));
            builder.append("&couponRuleId={couponRuleId}");
        }
        if (amount != null && amount != 0) {
            kv.put("amount", String.valueOf(amount));
            builder.append("&amount={amount}");
        }

        String result = salesApi.get(builder.toString(), kv, settingUtils.get());

    }
//	@Override
//	public void listMass(Long couponRuleId, String param) {
//
//		StringBuilder builder=new StringBuilder();
//		builder.append(salesApi.getCouponRuleBaseURL()+SalesApi.MASS_COUPON+".json?appKey={appKey}&appId={appId}&sign={sign}");
//		Map<String,String> kv = new HashMap<String,String>();
//		if(couponRuleId!=null && couponRuleId!=0){
//        	kv.put("couponRuleId", String.valueOf(couponRuleId));
//        	builder.append("&couponRuleId={couponRuleId}");
//        }
//		if(StringUtils.isNotBlank(param)){
//		    kv.put("param", param);
//		    builder.append("&param={param}");
//        }
//		System.out.println("param：" +param);
//		String result = salesApi.get(builder.toString(), kv, settingUtils.get());
//
//	}


    @Override
    public Page<Coupon> queryCoupon(Long ruleId, String code, String phone) {

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.FIND_COUPON
            + ".json?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (ruleId != null && ruleId != 0) {
            kv.put("ruleId", String.valueOf(ruleId));
            builder.append("&ruleId={ruleId}");
        }
        if (StringUtils.isNotBlank(code)) {
            kv.put("code", code);
            builder.append("&code={code}");
        }
        if (StringUtils.isNotBlank(phone)) {
            kv.put("phone", phone);
            builder.append("&phone={phone}");
        }

        String result = salesApi.get(builder.toString(), kv, settingUtils.get());
        List<Coupon> list = new ArrayList<Coupon>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code1 = jo.getInt("code");
            if (code1 == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Coupon>>() {
                }.getType());
            }
        }

        return new PageImpl<Coupon>(list, pageable, total);
    }

    public List<Coupon> findAll(Long ruleId) {

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.EXPORT_COUPON
            + ".json?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        if (ruleId != null && ruleId != 0) {
            kv.put("ruleId", String.valueOf(ruleId));
            builder.append("&ruleId={ruleId}");
        }
        String result = salesApi.get(builder.toString(), kv, settingUtils.get());
        List<Coupon> list = new ArrayList<Coupon>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(),
                    new TypeToken<List<com.ybkj.daijia.server.sales.Coupon>>() {
                    }.getType());
            }

        }

        return list;

    }


    @Override
    public Result<Coupon> updateCouponLapsed(Long id) {

        Result<Coupon> result = new Result<Coupon>();
        result.setSuccess(false);

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.INVALID_COUPON
            + "?id={id}&appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        if (null != id) {
            kv.put("id", String.valueOf(id));
        }
        String resultStr = salesApi.put(builder.toString(), kv, settingUtils.get());
        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }

        return result;

    }


    @Override
    public Result<Coupon> giftCoupon(String content, String carNumber, String name,
        String phone, Long[] companyIds, String startTime, String endTime,
        Long[] gradeIds, Integer[] type, Boolean[] allowOverdraw, Integer overDay,
        OrderType orderType,
        String sendTypes, String couponRuleId,
        String amount) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Coupon> result = new Result<Coupon>();

        MultiValueMap<String, String> kv1 = new LinkedMultiValueMap<String, String>();

        if (couponRuleId != null) {
            kv1.add("couponRuleId", couponRuleId);
        }
        if (amount != null) {
            kv1.add("amount", amount);
        }
        Long count = passengerApi
            .countPassenger(principal, carNumber, name, phone, companyIds, startTime, endTime,
                gradeIds, type, allowOverdraw, null);
        if (null == count || count <= 0) {
            result.setSuccess(false);
            result.setMessage("暂未查询到客户！");
            return result;
        } else {
            Long pages = count / 1000;  //每次生成1000条
            pages += 1L;
            for (int page = 0; page < pages.intValue(); page++) {
                List<Passenger> passengerList = passengerApi.findPassenger(
                    principal, carNumber, name, phone, companyIds,
                    startTime, endTime, gradeIds, type, allowOverdraw,
                    null, page, 1000);

                // if(CollectionUtils.isEmpty(passengerList)){
                // result.setSuccess(false);
                // result.setMessage("暂未查询到客户！");
                // return result;
                // }

                String passengerIds = "";
                String passengerPhones = "";

                for (Passenger passenger : passengerList) {
                    if (null != overDay && null != orderType) {
                        Date finishTime = null;
                        if (orderType.equals(OrderType.daijia)) {
                            Order order = orderMapper
                                .selectLastedOneFinishedByPassenger(passenger
                                    .getId());
                            if (null != order) {
                                finishTime = order.getFinishTime();
                            }
                        } else if (orderType.equals(OrderType.zhuanche)) {
                            com.ybkj.daijia.server.zhuan.Order order = zhuanApi
                                .selectLastedOneFinishedByPassenger(
                                    passenger.getId(),
                                    settingUtils.get()).getResult();
                            if (null != order) {
                                finishTime = order.getFinishTime();
                            }
                        } else if (orderType.equals(OrderType.errand)) {
                            com.ybkj.daijia.server.errand.Order order = errandApi
                                .selectLastedOneFinishedByPassenger(
                                    passenger.getId(),
                                    settingUtils.get()).getResult();
                            if (null != order) {
                                finishTime = order.getFinishTime();
                            }
                        } else if (orderType.equals(OrderType.freight)) {
                            com.ybkj.daijia.server.freight.Order order = freightApi
                                .selectLastedOneFinishedByPassenger(
                                    passenger.getId(),
                                    settingUtils.get()).getResult();
                            if (null != order) {
                                finishTime = order.getFinishTime();
                            }
                        }

                        if (null != finishTime) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(finishTime);
                            calendar.add(Calendar.DATE, overDay);
                            if (calendar.getTime().getTime() <= new Date()
                                .getTime()) {
                                passengerIds += passenger.getId() + ",";
                                passengerPhones += passenger.getPhone() + ",";

                            }
                        } else {
                            passengerIds += passenger.getId() + ",";
                            passengerPhones += passenger.getPhone() + ",";

                        }

                    } else {
                        passengerIds += passenger.getId() + ",";
                        passengerPhones += passenger.getPhone() + ",";

                    }
                }

                if (StringUtils.isBlank(passengerIds)) {
                    result.setSuccess(false);
                    result.setMessage("暂未查询到客户！");
                    return result;
                }

                kv1.add("passengerIds", passengerIds);
                kv1.add("passengerPhones", passengerPhones);

                String result1 = salesApi.post(salesApi.getCouponRuleBaseURL()
                    + SalesApi.GIFTCOUPON_COUPON, kv1, settingUtils.get());
                if (null != result1) {
                    JSONObject jo = new JSONObject(result1);
                    Integer code = jo.getInt("code");
                    if (code == 0) {
                        String[] couponruleid = couponRuleId.split(",");
                        String[] amountArr = amount.split(",");
                        String message = "亲，您好！您是我公司尊贵的VIP用户，感谢您长时间对我们公司的支持，我们悄悄的赠送了";
                        for (int i = 0; i < couponruleid.length; i++) {
                            Long couponAmount = 0L;
                            long id = Long.parseLong(couponruleid[i]);
                            CouponRule couponRule = salesApi.findOneCouponRule(
                                id).getResult();
                            if (null != couponRule) {
                                message += "【" + couponRule.getTitle() + "】券:";
                                if (!couponRule.isLapsed()
                                    && couponRule
                                    .getTimeStatus()
                                    .equals(CouponRule.COUPONRULE_STATUS_ONUSING)) {
                                    couponAmount = Long.valueOf(amountArr[i]);
                                }
                                message += couponAmount + "张 ";
                            }
                        }
                        message += "，更多优惠，敬请关注。";
                        ActivityGiftCouponEvent activityGiftCouponEvent = new ActivityGiftCouponEvent(
                            message, passengerList);
                        applicationEventMulticaster
                            .multicastEvent(activityGiftCouponEvent);

                        result.setSuccess(true);

                    } else {
                        result.setMessage(jo.getString("message"));
                    }
                }

            }
            return result;
        }

    }


    @Override
    public List<com.ybkj.daijia.server.model.Coupon> listAllOldByRule(Long ruleId) {
        return couponMapper.selectAllByRule(ruleId);
    }


    @Override
    public Result<Coupon> insert(Long passengerId, String phone,
        Long couponRuleId, Integer status, String code, Long runCode,
        String codeKey) {
        Result<Coupon> result = new Result<Coupon>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        if (null != passengerId) {
            kv.add("passengerId", String.valueOf(passengerId));
        }
        if (StringUtils.isNotBlank(phone)) {
            kv.add("phone", phone);
        }
        kv.add("couponRuleId", String.valueOf(couponRuleId));
        kv.add("status", String.valueOf(status));
        kv.add("code", code);
        kv.add("runCode", String.valueOf(runCode));
        if (StringUtils.isNotBlank(codeKey)) {
            kv.add("codeKey", codeKey);
        }

        String result1 = salesApi
            .post(salesApi.getCouponRuleBaseURL() + SalesApi.CREATE_COUPON, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result1);
        Integer code1 = jo.getInt("code");
        if (code1 == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            Coupon coupon = gson.fromJson(data.toString(), Coupon.class);
            result.setResult(coupon);
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }
        return result;
    }


}
